package com.none.staff.view.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.none.staff.R;
import com.none.staff.contract.ISplashContract;
import com.none.staff.contract.ISplashContract.ISplashView;
import com.none.staff.managers.SharePreferenceManager;
import com.none.staff.model.ConfigBean;
import com.none.staff.presenter.SplashPresenter;
import com.none.staff.services.UpdataApkService;
import com.none.staff.utils.Constants;
import com.none.staff.view.dialog.TipMessageDialogUtil;
import com.peter.baselibrary.utils.LogUtils;
import com.peter.electronicmall.base.BaseActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class SplashActivity extends BaseActivity implements ISplashView {

    private static String TAG = SplashActivity.class.getSimpleName();
    private ISplashContract.ISplashPresenter presenter = new SplashPresenter(SplashActivity.this);
    private TipMessageDialogUtil dialogUtil = new TipMessageDialogUtil(this);
    private TextView tv_timer;
    private ImageView imageView;
    CountDownTimer timer;
    ProgressBar progressBar;

    public static void startSplashActivity(Context context) {
        Intent intent = new Intent(context, SplashActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.onFinish();
        }
        presenter.detachView();
    }

    @Override
    public int getLayoutId() {
        presenter.attachView(this);
        return R.layout.activity_sp;
    }

    /**
     *
     */
    @Override
    public void initView() {
        presenter.isGoInGuide();
        tv_timer = findViewById(R.id.tv_timer);
        imageView = findViewById(R.id.img_s);
        progressBar = findViewById(R.id.progressbar_degree);
        requestPermissions();

    }

    private void sratrDownloadService(String url) {
        Intent intent = new Intent(this, UpdataApkService.class);
        intent.putExtra("downloadurl", url);
        startService(intent);
    }

    /**
     *
     */
    @TargetApi(Build.VERSION_CODES.M)
    @SuppressLint("CheckResult")
    private void requestPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.REQUEST_INSTALL_PACKAGES)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        LogUtils.INSTANCE.d(permission.name + " is granted.");
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        LogUtils.INSTANCE.d(permission.name + " is denied. More info should be provided.");
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        LogUtils.INSTANCE.d(permission.name + " is denied.");
                    }
                }, throwable -> {

                }, () -> {
                    LogUtils.INSTANCE.d(" is granted.");
                    presenter.getConfig(getResources().getString(R.string.config_url));
//                    countTimer();
                });
    }


    @Override
    public void initData() {

    }

    private void countTimer() {
        timer = new CountDownTimer(15000, 1500) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long l) {
                tv_timer.setText(l / 1500 - 1 + " s");
            }

            @Override
            public void onFinish() {
                HomeActivity.Companion.start(SplashActivity.this);
                finish();
            }
        };
        timer.start();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void getConfigSuccess() {
        if (presenter.checkNativeIsNeedUpgrade()) {
            presenter.downloadUpgradeAPKFile();
            return;
        }
        if (presenter.checkClientIsNeedUpgrade()) {
            presenter.downloadClientResource();
            return;
        }
        HomeActivity.Companion.start(SplashActivity.this);
        finish();

//        SharePreferenceManager sharePreferenceManager = new SharePreferenceManager(this);
//        ConfigBean oldConfigBean = new Gson().fromJson(sharePreferenceManager
//                .getSharedPreferences(Constants.SP_CONFIG_SHARED_NAME)
//                .getString(Constants.SP_APPLICATION_CONFIG_CONTENT, ""), ConfigBean.class);
//        String downloadPath;
////        if (oldConfigBean != null) {
////            downloadPath = oldConfigBean.getAppUpgradeLink();
////        } else {
//        downloadPath = "http://gltcreddownload.oss-cn-shenzhen.aliyuncs.com/UAT/red/v4.2/staff-RedUat.apk";
////        }
//        sratrDownloadService(downloadPath);
//        HomeActivity.Companion.start(SplashActivity.this);
//        finish();
    }

    @Override
    public void intoHomePage() {
        HomeActivity.Companion.start(SplashActivity.this);
        finish();
    }

    @Override
    public void getConfigFailed(String title, String msg) {
        dialogUtil.createTipDialog(title, msg);
        dialogUtil.builder.setPositiveButton(getResources().getString(R.string.retry), (dialogInterface, i) -> {
                    presenter.getConfig(getResources().getString(R.string.config_url));
                    dialogUtil.dismiss();
                }
        );
        dialogUtil.builder.setNegativeButton(getResources().getString(R.string.cancel), (dialogInterface, i) -> {
                    dialogUtil.dismiss();
                    this.finish();
                }
        );
        dialogUtil.show();
    }

    @Override
    public void downloadUpgrade(int progress) {
        progressBar.setProgress(progress);
    }

    @Override
    public void loading() {

    }


    @Override
    public void unLoading() {

    }

    @Override
    public void showIsUpgradeDialog() {
        dialogUtil.createTipDialog("版本升级", "正在升级，请勿关闭手机或App");
    }

    @Override
    public void showGuidePage() {
        Intent intent = new Intent(this, GuideActivity.class);
        startActivity(intent);
        finish();
    }


    @Override
    public void showToast(@NotNull String msg) {

    }

    @Override
    public void showLoading(@NotNull String title, @NotNull String msg) {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void onReConnect() {

    }
}
